//二叉树的右视图
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
    vector<int> ret;

public:
    vector<int> rightSideView(TreeNode* root) {
        if (!root)
            return ret;

        queue<TreeNode*> q;
        q.push(root);

        while (q.size()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode* t = q.front();
                if (i == size - 1)
                    ret.push_back(t->val);
                q.pop();
                if (t->left)
                    q.push(t->left);
                if (t->right)
                    q.push(t->right);
            }
        }

        return ret;
    }
};

// 二叉树展开为链表
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
    TreeNode* cur;

public:
    void flatten(TreeNode* root) {
        TreeNode* _head = new TreeNode(-1);
        cur = _head;
        dfs(root);
    }
    void dfs(TreeNode* root) {
        if (!root)
            return;

        TreeNode* left = root->left;
        TreeNode* right = root->right;
        cur->right = root;
        cur = cur->right;
        cur->left = nullptr;
        dfs(left);
        dfs(right);
    }
};